<template>
    <div class="app-container">
      <!-- 头部 -->
      <div class="header">
        <div>项目管理</div>
        <el-button type="primary" icon="el-icon-plus" @click="openAddDialog" size="mini">新增项目</el-button>
      </div>
      
      <!-- 搜索区域 -->
      <!-- <div class="search-bar">
        <el-input
          placeholder="请输入项目名称或描述"
          v-model="searchKeyword"
          @keyup.enter.native="filterProjects"
          clearable
          @clear="filterProjects"
        >
          <el-button slot="append" icon="el-icon-search" @click="filterProjects"></el-button>
        </el-input>
      </div> -->
      
      <!-- 项目表格 -->
      <el-table
        v-loading="loading"
        :data="filteredProjects"
        style="width: 100%"
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        :default-expand-all="false"
        :row-class-name="tableRowClassName"
        @row-click="handleRowClick"
        ref="menuTable"
      >
        <el-table-column prop="projectName" label="项目名称" >
          <template slot-scope="scope">
            <div class="project-name-cell">
              <!-- <i class="fas fa-folder project-icon"></i> -->
              <span>{{ scope.row.projectName }}</span>
              <el-tag v-if="scope.row.parentId === 0" size="mini" type="primary" style="margin-left: 10px;">根项目</el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="项目描述" ></el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180">
          <template slot-scope="scope">
            <i class="el-icon-refresh"></i> {{ formatDate(scope.row.updatedAt) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template slot-scope="scope">
            <i class="el-icon-time"></i> {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        
        
        
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template slot-scope="scope">
            <div class="operation-cell">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="confirmDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 无数据提示 -->
      <div v-if="filteredProjects.length === 0 && !loading" class="no-data">
        <i class="fas fa-inbox"></i>
        <p>没有找到匹配的项目</p>
      </div>
      
      <!-- 新增/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="form.projectName" placeholder="请输入项目名称"></el-input>
          </el-form-item>
          
          <el-form-item label="项目描述" prop="description">
            <el-input 
              type="textarea" 
              v-model="form.description" 
              placeholder="请输入项目描述"
              :autosize="{ minRows: 3, maxRows: 5 }"
            ></el-input>
          </el-form-item>
          
          <!-- <el-form-item label="父级项目" prop="parentId">
            <el-select v-model="form.parentId" placeholder="请选择父级项目" style="width: 100%">
              <el-option label="无父级项目 (根项目)" :value="0"></el-option>
              <el-option 
                v-for="project in rootProjects" 
                :key="project.id" 
                :label="project.projectName" 
                :value="project.id"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="父级项目" prop="parentId">
            <el-select 
              v-model="form.parentId" 
              placeholder="请选择父级项目" 
              style="width: 100%"
              class="parent-selector"
            >
              <el-option label="无父级项目 (根项目)" :value="0"></el-option>
              <el-option 
                v-for="project in availableParentProjects" 
                :key="project.id" 
                :label="project.projectName" 
                :value="project.id"
              >
                <div style="display: flex; align-items: center;">
                  <span :class="`level-${project.level}-indicator level-indicator`"></span>
                  <span>{{ project.projectName }}</span>
                  <el-tag v-if="project.parentId === 0" size="mini" type="primary" style="margin-left: 10px;">根项目</el-tag>
                </div>
              </el-option>
            </el-select>
            <div class="form-tips">
              注意：不能选择自身或自己的子项目作为父级
            </div>
          </el-form-item>
        </el-form>
        
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>
    
  </div>
</template>
<script>




export default {
  name: 'Program',  
  components: { },
  props: {

  },
  data(){
    return{
      // 存储所有可选的父级项目（排除自身及其子项目）
          availableParentProjects: [],
     loading: false,
          searchKeyword: '',
          projects: [],
          filteredProjects: [],
          dialogVisible: false,
          dialogTitle: '新增项目',
          form: {
            id: null,
            projectName: '',
            description: '',
            parentId: 0
          },
          rules: {
            projectName: [
              { required: true, message: '请输入项目名称', trigger: 'blur' },
              { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
            ],
            description: [
              { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
            ]
          }
    }
  },
  computed: {
    // 获取所有根项目（无父级的项目）
        rootProjects() {
          return this.projects.filter(p =>  p.id!=this.form.id);
        }
  },
  methods: {
  // 处理行点击事件
        handleRowClick(row, column, event) {
          // 检查点击是否在操作按钮上（避免与操作按钮冲突）
          if (event.target.closest('.operation-cell')) {
            return;
          }
          
          // 如果该行有子节点，则切换展开状态
          if (row.children && row.children.length > 0) {
            this.toggleRowExpansion(row);
          }
        },
        
        // 切换行展开状态
        toggleRowExpansion(row) {
          const table = this.$refs.menuTable;
          table.toggleRowExpansion(row);
        },
        // 为行添加类名，用于层级样式
        tableRowClassName({ row }) {
          if (row.level === undefined) return '';
          return `level-${row.level}`;
        },
        
        // 获取项目数据
        fetchProjects() {
          // this.loading = true;
          this.$axios.get('/api/services/hzsfjtai/project/treeList', {}).then(res => {
            if (res.data.code === 200) {
              this.projects =res.data.data.map(item => ({
                ...item,
                parentId: item.value == null ? 0 : item.value
              }));
              console.log(89,this.projects);
               // 为每个节点添加层级信息
              this.addLevelInfo(this.projects, 0);
              this.filteredProjects = [...this.projects];
              // this.loading = false;
            } else {
              this.$message(res.data.msg)
            }
          }).catch(err => {
            this.$message.error(err)
          })
          // 模拟API请求
          // setTimeout(() => {
          //   // 模拟数据
            //  this.projects = [
            //   {
            //     id: 1,
            //     projectName: '经济责任审计',
            //     description: '经济责任审计',
            //     parentId: 0,
            //     createdAt: '2023-01-15T08:30:00Z',
            //     updatedAt: '2023-06-10T14:20:00Z',
            //   },
            //   {
            //     id: 7,
            //     projectName: '财政收支审计',
            //     description: '财政收支审计',
            //     parentId: 0,
            //     createdAt: '2023-01-20T10:00:00Z',
            //     updatedAt: '2023-06-15T09:30:00Z',
            //     children: [
            //       {
            //         id: 8,
            //         projectName: '同级审',
            //         description: '同级审',
            //         parentId: 7,
            //         createdAt: '2023-02-25T14:20:00Z',
            //         updatedAt: '2023-05-30T16:40:00Z'
            //       },
            //       {
            //         id: 9,
            //         projectName: '部门预算执行',
            //         description: '部门预算执行',
            //         parentId: 7,
            //         createdAt: '2023-02-25T14:20:00Z',
            //         updatedAt: '2023-05-30T16:40:00Z'
            //       }
            //     ]
            //   },
            //   {
            //     id: 10,
            //     projectName: '自然资源资产',
            //     description: '自然资源资产',
            //     parentId: 0,
            //     createdAt: '2023-02-05T09:30:00Z',
            //     updatedAt: '2023-06-12T11:20:00Z'
            //   }
            // ];
            
          //   // 为每个节点添加层级信息
          //   this.addLevelInfo(this.projects, 0);
            
          //   this.filteredProjects = [...this.projects];
          //   this.loading = false;
          // }, 800);
        },
        
        // 递归添加层级信息
        addLevelInfo(nodes, level) {
          nodes.forEach(node => {
            node.level = level;
            if (node.children && node.children.length) {
              this.addLevelInfo(node.children, level + 1);
            }
          });
        },
        
        // 打开新增对话框
        openAddDialog() {
          this.dialogTitle = '新增项目';
          this.form = {
            id: null,
            projectName: '',
            description: '',
            parentId: 0
          };
          // 关键修改点1：获取所有可用的父级项目（所有项目）
          this.availableParentProjects = this.getAllProjects();
          this.dialogVisible = true;
          this.$nextTick(() => {
            if (this.$refs.form) {
              this.$refs.form.clearValidate();
            }
          });
        },
        
        // 打开编辑对话框
        openEditDialog(project) {
          this.dialogTitle = '编辑项目';
          this.form = {
            id: project.id,
            projectName: project.projectName,
            description: project.description,
            parentId: project.parentId
          };
          // 关键修改点2：获取所有可用的父级项目（排除自身及其子项目）
          this.availableParentProjects = this.getAvailableParentProjects(project.id);
          this.dialogVisible = true;
          this.$nextTick(() => {
            if (this.$refs.form) {
              this.$refs.form.clearValidate();
            }
          });
        },
        // 获取所有项目（扁平化结构）
        getAllProjects() {
          const result = [];
          const traverse = (nodes) => {
            nodes.forEach(node => {
              result.push({
                id: node.id,
                projectName: node.projectName,
                parentId: node.parentId,
                level: node.level
              });
              if (node.children && node.children.length) {
                traverse(node.children);
              }
            });
          };
          traverse(this.projects);
          return result;
        },
        // 获取可用的父级项目（排除自身及其子项目）
        getAvailableParentProjects(excludeId) {
          // 获取所有项目
          const allProjects = this.getAllProjects();
          
          // 获取要排除的项目ID（自身及其所有子项目）
          const excludeIds = this.getExcludedIds(excludeId);
          
          // 过滤出可用的项目
          return allProjects.filter(project => 
            !excludeIds.includes(project.id) && 
            project.id !== excludeId
          );
        },
        
        // 获取要排除的项目ID（递归获取所有子项目ID）
        getExcludedIds(parentId) {
          const excludedIds = [];
          const traverse = (nodes) => {
            nodes.forEach(node => {
              if (node.id === parentId || node.parentId === parentId) {
                excludedIds.push(node.id);
                if (node.children && node.children.length) {
                  traverse(node.children);
                }
              } else if (node.children && node.children.length) {
                traverse(node.children);
              }
            });
          };
          traverse(this.projects);
          return excludedIds;
        },
        
        // 提交表单
        submitForm() {
          this.$refs.form.validate(valid => {
            if (valid) {
              if (this.form.id) {
                // 更新项目
                this.updateProject();
              } else {
                // 新增项目
                this.addProject();
              }
              this.dialogVisible = false;
            }
          });
        },
        
        // 新增项目
        addProject() {
          // const newProject = {
          //   projectName: this.form.projectName,
          //   description: this.form.description,
          //   parentId: this.form.parentId,
          //   createdAt: new Date().toISOString(),
          //   updatedAt: new Date().toISOString(),
          //   level: this.form.parentId === 0 ? 0 : (this.getParentLevel(this.form.parentId) + 1)
          // };
          this.$axios.post('/api/services/hzsfjtai/project/add', {
            projectName: this.form.projectName,
            description: this.form.description,
            parentId: this.form.parentId === 0 ? null : this.form.parentId,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
          }).then(res => {
            if (res.data.code === 200) {
              this.fetchProjects();
              this.$message({
                type: 'success',
                message: '项目添加成功!'
              });
            } else {
              this.$message(res.data.msg)
            }
          }).catch(err => {
            this.$message.error(err)
          })
        },
        
        // 获取父级层级
        getParentLevel(parentId) {
          const parent = this.findProjectById(this.projects, parentId);
          return parent ? parent.level : 0;
        },
        
        // 递归查找项目
        findProjectById(projects, id) {
          for (const project of projects) {
            if (project.id === id) {
              return project;
            }
            
            if (project.children && project.children.length > 0) {
              const found = this.findProjectById(project.children, id);
              if (found) return found;
            }
          }
          return null;
        },
        
        // 递归添加子项目
        addChildProject(projects, parentId, newProject) {
          for (const project of projects) {
            if (project.id === parentId) {
              if (!project.children) {
                project.children = [];
              }
              project.children.push(newProject);
              return true;
            }
            
            if (project.children && project.children.length > 0) {
              if (this.addChildProject(project.children, parentId, newProject)) {
                return true;
              }
            }
          }
          return false;
        },
        
        // 更新项目
        updateProject() {
          this.$axios.post('/api/services/hzsfjtai/project/update', {
            id:this.form.id,
            projectName: this.form.projectName,
            description: this.form.description,
            parentId: this.form.parentId === 0 ? null : this.form.parentId,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
          }).then(res => {
            if (res.data.code === 200) {
                this.fetchProjects();
                this.$message({
                  type: 'success',
                  message: '项目更新成功!'
                });
            } else {
              this.$message(res.data.msg)
            }
          }).catch(err => {
            this.$message.error(err)
          })
          
         
        },
        
        // 递归更新项目
        updateProjectInTree(projects, updatedProject) {
          for (let i = 0; i < projects.length; i++) {
            if (projects[i].id === updatedProject.id) {
              projects[i] = {
                ...projects[i],
                projectName: updatedProject.projectName,
                description: updatedProject.description,
                parentId: updatedProject.parentId,
                updatedAt: new Date().toISOString()
              };
              return true;
            }
            
            if (projects[i].children && projects[i].children.length > 0) {
              if (this.updateProjectInTree(projects[i].children, updatedProject)) {
                return true;
              }
            }
          }
          return false;
        },
        
        // 确认删除
        confirmDelete(project) {
          this.$confirm(`确定删除项目 "${project.projectName}" 及其所有子项目吗?`, '删除确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteProject(project.id);
          }).catch(() => {});
        },
        
        // 删除项目
        deleteProject(id) {
          this.$axios.post('/api/services/hzsfjtai/project/delete', {
            id:id
          }).then(res => {
            if (res.data.code === 200) {
                this.fetchProjects();
                this.$message({
                  type: 'success',
                  message: '项目删除成功!'
                });
            } else {
              this.$message(res.data.msg)
            }
          }).catch(err => {
            this.$message.error(err)
          })
        },
        
        // 递归删除项目
        removeProjectFromTree(projects, id) {
          for (let i = 0; i < projects.length; i++) {
            if (projects[i].id === id) {
              projects.splice(i, 1);
              return true;
            }
            
            if (projects[i].children && projects[i].children.length > 0) {
              if (this.removeProjectFromTree(projects[i].children, id)) {
                return true;
              }
            }
          }
          return false;
        },
        
        // 过滤项目
        filterProjects() {
          if (!this.searchKeyword) {
            this.filteredProjects = [...this.projects];
            return;
          }
          
          const keyword = this.searchKeyword.toLowerCase();
          this.filteredProjects = this.deepFilterProjects(this.projects, keyword);
        },
        
        // 深度过滤项目
        deepFilterProjects(projects, keyword) {
          return projects.filter(project => {
            // 检查当前项目是否匹配
            const match = project.projectName.toLowerCase().includes(keyword) || 
                          (project.description && project.description.toLowerCase().includes(keyword));
            
            // 递归过滤子项目
            if (project.children && project.children.length > 0) {
              const filteredChildren = this.deepFilterProjects(project.children, keyword);
              if (filteredChildren.length > 0) {
                // 如果子项目匹配，则保留当前项目及其匹配的子项目
                project.children = filteredChildren;
                return true;
              }
            }
            
            // 如果当前项目匹配，则保留
            return match;
          });
        },
        
        // 格式化日期
        formatDate(isoString) {
          const date = new Date(isoString);
          return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
        },
        
        // 生成唯一ID
        generateId() {
          return Math.max(0, ...this.getAllIds(this.projects)) + 1;
        },
        
        // 获取所有项目ID
        getAllIds(projects) {
          let ids = [];
          projects.forEach(project => {
            ids.push(project.id);
            if (project.children && project.children.length > 0) {
              ids = ids.concat(this.getAllIds(project.children));
            }
          });
          return ids;
        }
      },
  mounted() {
    this.fetchProjects();
  }
}
</script>
<style scoped lang="less" >
.el-table__row {
  cursor: pointer;
  transition: background-color 0.3s;
}

.el-table__row:hover {
  background-color: #f0f7ff !important;
}

.el-table__row--expanded {
  background-color: #f5f7fa;
}
.app-container {
      // max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
    }
    
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #ebeef5;
    }
    
    .header h1 {
      color: #303133;
      font-weight: 600;
      font-size: 24px;
      display: flex;
      align-items: center;
      gap: 10px;
    }
    
    .header h1 i {
      color: #409EFF;
    }
    
    .search-bar {
      display: flex;
      gap: 10px;
      margin-bottom: 20px;
    }
    
    .search-bar .el-input {
      flex: 1;
    }
    
    .el-table {
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
    }
    
    .el-table .el-table__row:hover {
      background-color: #f5f7fa !important;
    }
    
    .el-table .el-table__row--level-0 {
      background-color: #f0f7ff;
    }
    
    .el-table .el-table__row--level-1 {
      background-color: #f9fbfd;
    }
    
    .el-table .el-table__row--level-2 {
      background-color: #fff;
    }
    
    .operation-cell {
      display: flex;
      gap: 8px;
    }
    
    .el-button--primary {
      background-color: #409EFF;
      border-color: #409EFF;
    }
    
    .el-button--primary:hover {
      background-color: #66b1ff;
      border-color: #66b1ff;
    }
    
    .el-button--primary:active {
      background-color: #3a8ee6;
      border-color: #3a8ee6;
    }
    
    .el-tag {
      border-radius: 12px;
      padding: 0 12px;
      height: 28px;
      line-height: 28px;
    }
    
    .el-tag--primary {
      background-color: #ecf5ff;
      border-color: #d9ecff;
      color: #409EFF;
    }
    
    .el-tag--success {
      background-color: #f0f9eb;
      border-color: #e1f3d8;
      color: #67c23a;
    }
    
    .no-data {
      text-align: center;
      padding: 40px 0;
      color: #909399;
    }
    
    .no-data i {
      font-size: 60px;
      color: #dcdfe6;
      margin-bottom: 15px;
    }
    
    .no-data p {
      font-size: 16px;
    }
    
    .el-dialog__header {
      border-bottom: 1px solid #ebeef5;
      padding: 15px 20px;
    }
    
    .el-dialog__title {
      color: #303133;
      font-weight: 600;
      font-size: 18px;
    }
    
    .el-dialog__body {
      padding: 20px;
    }
    
    .footer {
      text-align: center;
      padding: 20px 0;
      color: #909399;
      font-size: 14px;
    }
    
    .footer a {
      color: #409EFF;
      text-decoration: none;
    }
    
    .footer a:hover {
      text-decoration: underline;
    }
    
    .project-icon {
      color: #409EFF;
      margin-right: 8px;
    }
    
    /* 优化树形表格样式 */
    .el-table .el-table__row .el-table__expand-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      position: relative;
      top: 0;
    }
    
    .el-table .el-table__row .el-table__expand-icon .el-icon {
      margin-top: -2px;
    }
    
    .el-table .cell {
      display: flex;
      align-items: center;
      height: 100%;
    }
    
    /* 层级缩进样式 */
    .project-name-cell {
      display: flex;
      align-items: center;
      height: 100%;
      padding-left: 10px;
    }
    
    .level-indent {
      display: inline-block;
      width: 24px;
      height: 100%;
    }
    
    .level-1 .project-name-cell {
      padding-left: 34px; /* 24px (一级缩进) + 10px */
    }
    
    .level-2 .project-name-cell {
      padding-left: 58px; /* 48px (两级缩进) + 10px */
    }
    
    .level-3 .project-name-cell {
      padding-left: 82px; /* 72px (三级缩进) + 10px */
    }
    
    .level-0 .el-table__expand-icon {
      color: #409EFF;
    }
    
    .level-1 .el-table__expand-icon {
      color: #67C23A;
    }
    
    .level-2 .el-table__expand-icon {
      color: #E6A23C;
    }
    
    .level-3 .el-table__expand-icon {
      color: #F56C6C;
    }
    
    .el-table__expand-icon--expanded {
      transform: rotate(0);
    }
    
    .el-table__expand-icon .el-icon-arrow-right:before {
      content: "\e6d9";
    }
    
    .el-table__expand-icon--expanded .el-icon-arrow-right:before {
      content: "\e6d8";
    }
</style>

